﻿namespace Cellfish.Toolbox.Streams
{
    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;

    using Cellfish.Toolbox.Tasks;

    /// <summary>
    /// Implemets a stream wrapper where you can intercept reads and writes both
    /// before and after reads and writes. 
    /// BeforeRead and BeforeWrite will be called indicating how much data is requested to
    /// be read/written. AfterRead/Write will actually tell you how much data was actually 
    /// read/written.
    /// Argument errors are reported to the before observer and all other errors to the after observer.
    /// </summary>
    public class PassThruStream : Stream
    {
        private readonly Stream stream;

        private IObserver<BeforeData> beforeRead = new DefaultBeforeObserver();

        private IObserver<int> afterRead = new DefaultAfterObserver();

        private IObserver<BeforeData> beforeWrite = new DefaultBeforeObserver();

        private IObserver<int> afterWrite = new DefaultAfterObserver();

        /// <summary>
        /// Initializes a new instance of the <see cref="PassThruStream" /> class.
        /// </summary>
        /// <param name="stream">The stream to wrap.</param>
        /// <param name="beforeRead">The before read observer.</param>
        /// <param name="afterRead">The after read observer.</param>
        /// <param name="beforeWrite">The before write observer.</param>
        /// <param name="afterWrite">The after write observer.</param>
        /// <exception cref="System.ArgumentNullException">If stream is null.</exception>
        public PassThruStream(
            Stream stream,
            IObserver<BeforeData> beforeRead = null,
            IObserver<int> afterRead = null,
            IObserver<BeforeData> beforeWrite = null,
            IObserver<int> afterWrite = null)
        {
            if (stream == null)
            {
                throw new ArgumentNullException();
            }

            this.stream = stream;
            this.BeforeRead = beforeRead;
            this.AfterRead = afterRead;
            this.BeforeWrite = beforeWrite;
            this.AfterWrite = afterWrite;
        }

        /// <summary>
        /// Sets the before read observer.
        /// </summary>
        /// <value>
        /// The before read observer.
        /// </value>
        protected IObserver<BeforeData> BeforeRead
        {
            set
            {
                this.beforeRead = value ?? new DefaultBeforeObserver();
            }
        }

        /// <summary>
        /// Sets the after read observer.
        /// </summary>
        /// <value>
        /// The after read observer.
        /// </value>
        protected IObserver<int> AfterRead
        {
            set
            {
                this.afterRead = value ?? new DefaultAfterObserver();
            }
        }

        /// <summary>
        /// Sets the before write observer.
        /// </summary>
        /// <value>
        /// The before write observer.
        /// </value>
        protected IObserver<BeforeData> BeforeWrite
        {
            set
            {
                this.beforeWrite = value ?? new DefaultBeforeObserver();
            }
        }

        /// <summary>
        /// Sets the after write observer.
        /// </summary>
        /// <value>
        /// The after write observer.
        /// </value>
        protected IObserver<int> AfterWrite
        {
            set
            {
                this.afterWrite = value ?? new DefaultAfterObserver();
            }
        }

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
        /// </summary>
        /// <returns>true if the stream supports reading; otherwise, false.</returns>
        public override bool CanRead
        {
            get
            {
                return this.stream.CanRead;
            }
        }

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
        /// </summary>
        /// <returns>true if the stream supports seeking; otherwise, false.</returns>
        public override bool CanSeek
        {
            get
            {
                return this.stream.CanSeek;
            }
        }

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
        /// </summary>
        /// <returns>true if the stream supports writing; otherwise, false.</returns>
        public override bool CanWrite
        {
            get
            {
                return this.stream.CanWrite;
            }
        }

        /// <summary>
        /// When overridden in a derived class, gets the length in bytes of the stream.
        /// </summary>
        /// <returns>A long value representing the length of the stream in bytes.</returns>
        public override long Length
        {
            get
            {
                return this.stream.Length;
            }
        }

        /// <summary>
        /// When overridden in a derived class, gets or sets the position within the current stream.
        /// </summary>
        /// <returns>The current position within the stream.</returns>
        public override long Position
        {
            get
            {
                return this.stream.Position;
            }

            set
            {
                this.stream.Position = value;
            }
        }

        /// <summary>
        /// Gets a value that determines whether the current stream can time out.
        /// </summary>
        /// <returns>A value that determines whether the current stream can time out.</returns>
        public override bool CanTimeout
        {
            get
            {
                return this.stream.CanTimeout;
            }
        }

        /// <summary>
        /// Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out.
        /// </summary>
        /// <returns>A value, in miliseconds, that determines how long the stream will attempt to read before timing out.</returns>
        public override int ReadTimeout
        {
            get
            {
                return this.stream.ReadTimeout;
            }

            set
            {
                this.stream.ReadTimeout = value;
            }
        }

        /// <summary>
        /// Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out.
        /// </summary>
        /// <returns>A value, in miliseconds, that determines how long the stream will attempt to write before timing out.</returns>
        public override int WriteTimeout
        {
            get
            {
                return this.stream.WriteTimeout;
            }

            set
            {
                this.stream.WriteTimeout = value;
            }
        }

        /// <summary>
        /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// </summary>
        public override void Flush()
        {
            this.stream.Flush();
        }

        /// <summary>
        /// Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>
        /// A task that represents the asynchronous flush operation.
        /// </returns>
        public override Task FlushAsync(CancellationToken cancellationToken)
        {
            return this.stream.FlushAsync(cancellationToken);
        }

        /// <summary>
        /// When overridden in a derived class, sets the position within the current stream.
        /// </summary>
        /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param>
        /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param>
        /// <returns>
        /// The new position within the current stream.
        /// </returns>
        public override long Seek(long offset, SeekOrigin origin)
        {
            return this.stream.Seek(offset, origin);
        }

        /// <summary>
        /// When overridden in a derived class, sets the length of the current stream.
        /// </summary>
        /// <param name="value">The desired length of the current stream in bytes.</param>
        public override void SetLength(long value)
        {
            this.stream.SetLength(value);
        }

        /// <summary>
        /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            try
            {
                this.beforeRead.OnNext(new BeforeData(buffer, offset, count));
                var result = this.stream.Read(buffer, offset, count);
                this.afterRead.OnNext(result);
                return result;
            }
            catch (ArgumentException argEx)
            {
                this.beforeRead.OnError(argEx);
                throw;
            }
            catch (Exception ex)
            {
                this.afterRead.OnError(ex);
                throw;
            }
        }

        /// <summary>
        /// Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.
        /// </summary>
        /// <param name="buffer">The buffer to write the data into.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data from the stream.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>
        /// A task that represents the asynchronous read operation. The value of the task contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached.
        /// </returns>
        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            try
            {
                this.beforeRead.OnNext(new BeforeData(buffer, offset, count));
                return this.CompleteReadAsync(this.stream.ReadAsync(buffer, offset, count, cancellationToken));
            }
            catch (Exception ex)
            {
                this.beforeRead.OnError(ex);
                throw;
            }
        }

        private async Task<int> CompleteReadAsync(Task<int> readTask)
        {
            try
            {
                var result = await readTask;
                this.afterRead.OnNext(result);
                return result;
            }
            catch (Exception ex)
            {
                this.afterRead.OnError(ex);
                throw;
            }
        }

        /// <summary>
        /// Begins an asynchronous read operation. (Consider using <see cref="M:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="buffer">The buffer to read the data into.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data read from the stream.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
        /// <returns>
        /// An <see cref="T:System.IAsyncResult" /> that represents the asynchronous read, which could still be pending.
        /// </returns>
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            return this.ReadAsync(buffer, offset, count).ToApm(callback, state);
        }

        /// <summary>
        /// Waits for the pending asynchronous read to complete. (Consider using <see cref="M:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
        /// <returns>
        /// The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available.
        /// </returns>
        public override int EndRead(IAsyncResult asyncResult)
        {
            return asyncResult.EndTask<int>();
        }

        /// <summary>
        /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        public override void Write(byte[] buffer, int offset, int count)
        {
            try
            {
                this.beforeWrite.OnNext(new BeforeData(buffer, offset, count));
                this.stream.Write(buffer, offset, count);
                this.afterWrite.OnNext(count);
            }
            catch (ArgumentException argEx)
            {
                this.beforeWrite.OnError(argEx);
                throw;
            }
            catch (Exception ex)
            {
                this.afterWrite.OnError(ex);
                throw;
            }
        }

        /// <summary>
        /// Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> from which to begin copying bytes to the stream.</param>
        /// <param name="count">The maximum number of bytes to write.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>
        /// A task that represents the asynchronous write operation.
        /// </returns>
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            try
            {
                this.beforeWrite.OnNext(new BeforeData(buffer, offset, count));
                return this.CompleteWriteAsync(this.stream.WriteAsync(buffer, offset, count, cancellationToken), count);
            }
            catch (Exception ex)
            {
                this.beforeWrite.OnError(ex);
                throw;
            }
        }

        private async Task CompleteWriteAsync(Task writeTask, int bytes)
        {
            try
            {
                await writeTask;
                this.afterWrite.OnNext(bytes);
            }
            catch (Exception ex)
            {
                this.afterWrite.OnError(ex);
                throw;
            }
        }

        /// <summary>
        /// Begins an asynchronous write operation. (Consider using <see cref="M:System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> from which to begin writing.</param>
        /// <param name="count">The maximum number of bytes to write.</param>
        /// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
        /// <returns>
        /// An IAsyncResult that represents the asynchronous write, which could still be pending.
        /// </returns>
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            return this.WriteAsync(buffer, offset, count).ToApm(callback, state);
        }

        /// <summary>
        /// Ends an asynchronous write operation. (Consider using <see cref="M:System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
        /// </summary>
        /// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
        public override void EndWrite(IAsyncResult asyncResult)
        {
            asyncResult.EndTask();
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.stream.Dispose();
                this.beforeRead.OnCompleted();
                this.afterRead.OnCompleted();
                this.beforeWrite.OnCompleted();
                this.afterWrite.OnCompleted();
            }
        }

        /// <summary>
        /// Class holding data for the before observers.
        /// </summary>
        public class BeforeData
        {
            internal BeforeData(byte[] buffer, int offset, int count)
            {
                this.Buffer = buffer;
                this.Offset = offset;
                this.Count = count;
            }

            /// <summary>
            /// Gets the buffer.
            /// </summary>
            /// <value>
            /// The buffer.
            /// </value>
            public byte[] Buffer { get; private set; }

            /// <summary>
            /// Gets the offset.
            /// </summary>
            /// <value>
            /// The offset.
            /// </value>
            public int Offset { get; private set; }

            /// <summary>
            /// Gets the count.
            /// </summary>
            /// <value>
            /// The count.
            /// </value>
            public int Count { get; private set; }
        }

        private class DefaultBeforeObserver : IObserver<BeforeData>
        {
            public void OnNext(BeforeData value)
            {
            }

            public void OnError(Exception error)
            {
            }

            public void OnCompleted()
            {
            }
        }

        private class DefaultAfterObserver : IObserver<int>
        {
            public void OnNext(int value)
            {
            }

            public void OnError(Exception error)
            {
            }

            public void OnCompleted()
            {
            }
        }
    }
}